from flask import Blueprint, request, jsonify, g
from app.models.device_api_config import DeviceApiConfig
from app.models.venue import Venue
from app.extensions import db
from app.utils.decorators import admin_required
import requests
import json

bp = Blueprint('device_api_configs', __name__)

# 3.1. 获取API配置列表 & 3.2. 添加新的API配置
@bp.route('/venues/<int:venue_id>/device-api-configs', methods=['GET', 'POST'])
@admin_required
def handle_device_api_configs(venue_id):
    if request.method == 'GET':
        device_type = request.args.get('type')
        if not device_type:
            return jsonify(code=400, message="错误：必须提供 'type' 参数"), 400

        # 支持查询所有类型的设备配置
        if device_type.lower() == 'all':
            configs = DeviceApiConfig.query.filter_by(venue_id=venue_id).all()
        else:
            configs = DeviceApiConfig.query.filter_by(venue_id=venue_id, device_type=device_type).all()
            
        return jsonify(code=200, message="获取成功", data=[config.to_dict(full=True) for config in configs])

    if request.method == 'POST':
        data = request.get_json()
        if not data:
            return jsonify(code=400, message="错误：请求体不能为空"), 400

        if not Venue.query.get(venue_id):
            return jsonify(code=404, message="错误：找不到指定的场馆"), 404

        name = data.get('name')
        device_type = data.get('device_type')
        api_endpoint = data.get('api_endpoint')
        http_method = data.get('http_method', 'POST')

        if not all([name, device_type, api_endpoint]):
            return jsonify(code=400, message="错误：名称、设备类型和API端点是必填项"), 400

        new_config = DeviceApiConfig(
            venue_id=venue_id,
            name=name,
            description=data.get('description'),
            device_type=device_type,
            api_endpoint=api_endpoint,
            http_method=http_method.upper(),
            headers_template=data.get('headers_template'),
            body_template=data.get('body_template')
        )
        db.session.add(new_config)
        db.session.commit()

        return jsonify(code=200, message="创建成功", data=new_config.to_dict()), 200

# 3.3. 获取单个API配置详情
@bp.route('/device-api-configs/<int:config_id>', methods=['GET'])
@admin_required
def get_device_api_config(config_id):
    config = DeviceApiConfig.query.get_or_404(config_id)
    return jsonify(code=200, message="获取成功", data=config.to_dict())

# 3.4. 更新API配置
@bp.route('/device-api-configs/<int:config_id>', methods=['PUT'])
@admin_required
def update_device_api_config(config_id):
    config = DeviceApiConfig.query.get_or_404(config_id)
    data = request.get_json()
    if not data:
        return jsonify(code=400, message="错误：请求体不能为空"), 400

    # 更新字段
    config.name = data.get('name', config.name)
    config.description = data.get('description', config.description)
    config.device_type = data.get('device_type', config.device_type)
    config.api_endpoint = data.get('api_endpoint', config.api_endpoint)
    config.http_method = data.get('http_method', config.http_method).upper()
    config.headers_template = data.get('headers_template', config.headers_template)
    config.body_template = data.get('body_template', config.body_template)
    config.status = data.get('status', config.status)

    db.session.commit()
    return jsonify(code=200, message="更新成功", data=config.to_dict())

# 3.5. 删除API配置
@bp.route('/device-api-configs/<int:config_id>', methods=['DELETE'])
@admin_required
def delete_device_api_config(config_id):
    config = DeviceApiConfig.query.get_or_404(config_id)
    db.session.delete(config)
    db.session.commit()
    return jsonify(code=200, message="删除成功")

# 4.1. 执行一个API调用
@bp.route('/device-api-configs/<int:config_id>/execute', methods=['POST'])
@admin_required
def execute_device_api(config_id):
    config = DeviceApiConfig.query.get_or_404(config_id)
    if config.status != 'active':
        return jsonify(code=400, message="错误：此API配置当前未激活"), 400

    req_data = request.get_json() or {}
    placeholders = req_data.get('placeholders', {})

    # 准备请求参数
    method = config.http_method.upper()
    url = config.api_endpoint
    headers = config.headers_template or {}
    
    # 渲染 body 模板
    body_str = json.dumps(config.body_template or {})
    for key, value in placeholders.items():
        body_str = body_str.replace(f'"{{{{{key}}}}}"', json.dumps(value))

    body = json.loads(body_str)

    try:
        # 发起第三方请求
        response = requests.request(
            method=method,
            url=url,
            headers=headers,
            json=body if method in ['POST', 'PUT', 'PATCH'] else None,
            params=body if method == 'GET' else None,
            timeout=10 # 设置10秒超时
        )
        response.raise_for_status() # 如果状态码不是 2xx, 抛出异常

        try:
            # 尝试解析第三方返回的JSON
            third_party_data = response.json()
        except json.JSONDecodeError:
            # 如果不是JSON，直接返回文本内容
            third_party_data = response.text

        return jsonify(code=200, message="执行成功", data=third_party_data)

    except requests.exceptions.RequestException as e:
        return jsonify(code=500, message=f"执行第三方API时出错: {str(e)}"), 500 